package admin.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.CoordinaModel;
import models.OrderModel;
import models.OrderProductModel;
import models.RouteModel;
import models.StoreItemModel;
import search.OrderSearchData;
import admin.data.CoordinaData;
import admin.data.IdCountData;
import admin.data.RouteData;
import admin.data.StoreItemData;
import data.OrderData;

@SuppressWarnings("serial")
public class AddCoordinaServlet extends HttpServlet {
	@SuppressWarnings("rawtypes")
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		TreeMap check = new TreeMap();
		RouteData routeData = new RouteData();
		List<RouteModel> listRoute = routeData.getListRoute();
		TreeMap<String, CoordinaData> listCoordina = new TreeMap<String, CoordinaData>();

		request.setAttribute("check", check);
		request.setAttribute("listRoute", listRoute);
		request.setAttribute("listCoordina", listCoordina);

		try {
			request.getRequestDispatcher("/admin/pages/add_coordina.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		String action = (String) request.getParameter("action");
		
		if (action.equalsIgnoreCase("checkCoordina")) {
			String listOrder = (String) request.getParameter("listOrder");
			int totalOrder = 0;
			try {
				totalOrder = Integer.parseInt(request.getParameter("totalOrder"));
			} catch (Exception e) {
				totalOrder = 0;
			}
			if ((totalOrder > 0) && (listOrder != null)) {
				List<OrderModel> listOrderModel = new ArrayList<OrderModel>();
				String[] arrOrder = listOrder.split(",");
				for (int i = 0; i < arrOrder.length; i++) {
					if(arrOrder[i].length()>8)
					{
						OrderModel orderModel = OrderData.getOrder(arrOrder[i]);
						if (orderModel != null) {
							listOrderModel.add(orderModel);
						}
					}
				}
				Collections.sort(listOrderModel);
				TreeMap<String, CoordinaData> listSelectCoordina = new TreeMap<String, CoordinaData>();
				for (int i = 0; i < listOrderModel.size(); i++) {
					if (i + 1 > totalOrder) {
						break;
					}
					List<String> listOrderProduct = listOrderModel.get(i).getListOrderProduct();
					for (String stringOrderProduct : listOrderProduct) {
						OrderProductModel orderProduct = new OrderProductModel();
						orderProduct.getValueFromString(stringOrderProduct);
						if(listSelectCoordina.containsKey(orderProduct.getProductId()))
						{
							CoordinaData oldCoordina = listSelectCoordina.get(orderProduct.getProductId());
							oldCoordina.setQuantity(orderProduct.getQuantity()+oldCoordina.getQuantity());
						}
						else
						{
							CoordinaData coor = new CoordinaData();
							coor.setDealId(listOrderModel.get(i).getDealId());
							coor.setDealName(listOrderModel.get(i).getDealShortName());
							coor.setProductId(orderProduct.getProductId());
							coor.setProductName(orderProduct.getName());
							coor.setQuantity(orderProduct.getQuantity());
							coor.setStoreType(listOrderModel.get(i).getDealProductType());
							StoreItemData storeItemData = new StoreItemData();
							StoreItemModel storeItemModel = storeItemData.getItem(orderProduct.getProductId());
							coor.setInventory(storeItemModel.getInventory());							
							listSelectCoordina.put(orderProduct.getProductId(), coor);
						}
					}				
				}
				response.setCharacterEncoding("UTF-8");
				String listSelectResponse = "";
				for (Map.Entry<String, CoordinaData> entry : listSelectCoordina.entrySet()) {
					listSelectResponse += "<tr>";
					listSelectResponse += "<td>"+"["+entry.getValue().getDealId()+"] "+entry.getValue().getDealName()+"</td>";
					listSelectResponse += "<td>"+"["+entry.getValue().getProductId()+"] ";
						if(entry.getValue().getStoreType()==0) { listSelectResponse += " VC- ";}
						if(entry.getValue().getStoreType()==1) { listSelectResponse += " SP- ";}
						listSelectResponse += entry.getValue().getProductName()+"</td>";
					listSelectResponse += "<td class=\"center\">"+entry.getValue().getQuantity()+"</td>";					
					listSelectResponse += "<td class=\"center\">"+entry.getValue().getInventory()+"</td>";
					listSelectResponse += "</tr>";
				}
				response.getWriter().println(listSelectResponse);
			}
		}		
		
		if (action.equalsIgnoreCase("saveCoordina")) {
			String routeId = (String) request.getParameter("routeId");
			int totalOrder = 0;
			try {
				totalOrder = Integer.parseInt(request.getParameter("totalOrder"));
			} catch (Exception e) {
				totalOrder = 0;
			}
			String[] parameterValues = null;
			try {
				parameterValues = request.getParameterValues("checkbox");
			} catch (Exception e) {
				parameterValues = null;
			}
			if ((totalOrder > 0) && (parameterValues != null)) {
				List<String> listIdOrder = new ArrayList<String>();
				for (int i = 0; i < parameterValues.length; i++) {
					String[] listValues = parameterValues[i].split(",");
					for (int j = 0; j < listValues.length; j++) {
						listIdOrder.add(listValues[j]);
					}
				}
				List<OrderModel> listOrder = new ArrayList<OrderModel>();
				for (int i = 0; i < listIdOrder.size(); i++) {
					OrderModel orderModel = OrderData.getOrder(listIdOrder.get(i));
					if (orderModel != null) {
						listOrder.add(orderModel);
					}
				}
				Collections.sort(listOrder);
				String listOrderCoor = "";
				for (int i = 0; i < listOrder.size(); i++) {
					if (i + 1 > totalOrder) {
						break;
					}
					listOrderCoor+=listOrder.get(i).getOrderId()+",";
				}
				
				CoordinaModel coordinaModel = new CoordinaModel();
				coordinaModel.setListOrder(listOrderCoor);
				coordinaModel.setRouteId(routeId);
				coordinaModel.setStatus(0);
				coordinaModel.setCreated(new Date());
				
				Calendar cal = Calendar.getInstance();
				cal.setTime(coordinaModel.getCreated());
				String coordinaId = String.format("%02d",cal.get(Calendar.MONTH)+1) + String.format("%02d",cal.get(Calendar.DATE)) +"-"+ IdCountData.getIdByType("5");
				coordinaModel.setId(coordinaId);

				CoordinaData coordinaData = new CoordinaData();
				coordinaData.insert(coordinaModel);
				
				String[] list = listOrderCoor.split(",");
				for (int i = 0; i < list.length; i++) {
					if (list[i].length() > 9) {
						OrderModel orderModel = OrderData.getOrder(list[i]);
						orderModel.setStatus(2);
						OrderData.insert(orderModel);
					}
				}
				HttpSession session = request.getSession();
				session.setAttribute("success", "Xuất tuyến thành công !");
			} else {
				HttpSession session = request.getSession();
				session.setAttribute("alert", "Bạn chưa chọn đơn hàng hoặc số lượng đơn hàng sai !");
			}

			response.sendRedirect("/admin/coordina/add");
		}

		if (action.equalsIgnoreCase("listRoute")) {
			TreeMap check = new TreeMap();
			RouteData routeData = new RouteData();
			RouteModel routeModel = new RouteModel();
			OrderData orderData = new OrderData();

			String routeId = (String) request.getParameter("routeId");

			if ((routeId == null || routeId.equals(""))) {
				check.put("name", "Bạn chưa chọn tuyến.");
			}
			routeModel = routeData.getRoute(routeId);
			String listGeo = routeModel.getListGeoId();
			TreeMap<String, CoordinaData> listCoordina = new TreeMap<String, CoordinaData>();
			TreeMap<String, Integer> listStoreItem = new TreeMap<String, Integer>();
			if (listGeo.length() > 5) {
				String[] ward = listGeo.split(",");
				for (int i = 0; i < ward.length; i++) {
					OrderSearchData search = new OrderSearchData();
					search.searchOrderByWard(ward[i]);
					List<OrderModel> list = search.getListResult();
					for (int j = 0; j < list.size(); j++) {
						OrderModel orderModel = list.get(j);
						List<String> listOrderProduct = orderModel.getListOrderProduct();
						int k=0;
						for (String stringOrderProduct : listOrderProduct) {
							OrderProductModel orderProduct = new OrderProductModel();
							orderProduct.getValueFromString(stringOrderProduct);
							if(!listStoreItem.containsKey(orderProduct.getProductId()))
							{
								StoreItemData storeItemData = new StoreItemData();
								StoreItemModel storeItemModel = storeItemData.getItem(orderProduct.getProductId());
								listStoreItem.put(orderProduct.getProductId(), storeItemModel.getInventory());
							}							
							int inventory = listStoreItem.get(orderProduct.getProductId());								
							if(orderProduct.getQuantity() > inventory)
							{
								k=1;
							}
							else
							{
								inventory = inventory - orderProduct.getQuantity();
								listStoreItem.put(orderProduct.getProductId(), inventory);
							}
						}					
						
						if(k==0)
						{
							CoordinaData coor = new CoordinaData();
							if (listCoordina.containsKey(orderModel.getDealId())) {
								coor = listCoordina.get(orderModel.getDealId());
								coor.setOrderNumber(coor.getOrderNumber() + 1);
								coor.setListOrderId(coor.getListOrderId() + "," + orderModel.getOrderId());
							} else {
								coor.setDealId(orderModel.getDealId());
								coor.setDealName(orderModel.getDealShortName());
								coor.setStoreType(orderModel.getDealProductType());
								coor.setOrderNumber(1);
								coor.setListOrderId(orderModel.getOrderId());
							}
							for (String stringOrderProduct : listOrderProduct) {
								OrderProductModel orderProduct = new OrderProductModel();
								orderProduct.getValueFromString(stringOrderProduct);
								coor.addProduct(orderProduct);
							}						
	
							listCoordina.put(orderModel.getDealId(), coor);
						}
					}
				}
			}
			for (Map.Entry<String, CoordinaData> entry : listCoordina.entrySet()) {
				for (Map.Entry<String, OrderProductModel> product : entry.getValue().getProducts().entrySet()) {
					StoreItemData storeItemData = new StoreItemData();
					StoreItemModel storeItemModel = storeItemData.getItem(product.getValue().getProductId());
					product.getValue().setInventory(storeItemModel.getInventory());
					entry.getValue().getProducts().put(product.getKey(), product.getValue());
				}

			}
			List<RouteModel> listRoute = routeData.getListRoute();
			request.setAttribute("routeId", routeId);
			request.setAttribute("check", check);
			request.setAttribute("listRoute", listRoute);
			request.setAttribute("listCoordina", listCoordina);

			try {
				request.getRequestDispatcher("/admin/pages/add_coordina.jsp").forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
